<script lang="ts" setup>
import { ref, reactive } from "vue"
// import * as echarts from "echarts"
import dayjs from "dayjs"
import "echarts/renderers"
import { companyMonthlyTradeDataApi } from "@/api/conventional"
import eacharts from "./eacharts.vue"

const eachartsRef = ref<any>(null)
const currentDate = dayjs()
const dialogVisible = ref<boolean>(false)
const loading = ref<boolean>(false)
const handleClose = (done: () => void) => {
  cancelForm()
  done()
}
const cancelForm = () => {
  dateList.value = []
  searchData.id = 0
  tableData.value = []
  searchData.month = currentDate.format("MM")
  searchData.year = currentDate.format("YYYY")
  searchData.lastyear = currentDate.subtract(1, "year").format("YYYY")
}
const tableList = ref<any[]>([])
const tableLastList = ref<any[]>([])
const dateList = ref<any[]>([])
// const chartRef = ref<any>(null)
const dialogShow = async (row: any) => {
  console.log("dialogShow")
  console.log(row)
  companyName.value = row.company_name
  dialogVisible.value = true
  searchData.id = row.enter_company_id
  await getTableYearData()
  await getTableLastYearData()
  // await getTableData()
  // nextTick(() => {
  //   eaChartss()
  // })
}
defineExpose({ dialogShow })

//#region 查
const companyName = ref<string>("")
const yearList = reactive({
  total_enter_trade_amount: 0,
  total_out_trade_amount: 0
})
const yearLastList = reactive({
  total_enter_trade_amount: 0,
  total_out_trade_amount: 0
})
const tableData = ref<any[]>([])
const searchData = reactive({
  id: 0,
  dateType: "month",
  year: currentDate.format("YYYY"),
  month: currentDate.format("MM"),
  lastyear: currentDate.subtract(1, "year").format("YYYY")
})
const handleDatePickerChange = (value: string) => {
  searchData.year = value
  getTableYearData()
  getTableLastYearData()
  // getTableData()
}

const getMonthValue = (monthName: string): string | null => {
  const monthsMap = {
    一月: "01",
    二月: "02",
    三月: "03",
    四月: "04",
    五月: "05",
    六月: "06",
    七月: "07",
    八月: "08",
    九月: "09",
    十月: "10",
    十一月: "11",
    十二月: "12"
  } as const

  return monthsMap[monthName as keyof typeof monthsMap] || null
}

const handleDatePickerDate = (value: string, index: number) => {
  searchData.month = value
  console.log(value)
  let year
  if (index == 1) {
    year = searchData.lastyear
  } else {
    year = searchData.year
  }
  openDialogs({
    id: searchData.id,
    year: year,
    month: getMonthValue(value),
    company_name: companyName.value
  })
  // getTableData()
}
// const getTableData = () => {
//   loading.value = true
//   companyMonthlyTradeDataApi({
//     ...searchData
//   })
//     .then((res) => {
//       tableData.value = res.data
//       dateList.value = res.date
//       console.log(res)
//     })
//     .catch(() => {
//       tableData.value = []
//     })
//     .finally(() => {
//       loading.value = false
//     })
// }
// 转为 async/await 写法
// const getTableData = async () => {
//   loading.value = true
//   try {
//     searchData.dateType = "month"
//     const res = await companyMonthlyTradeDataApi({
//       ...searchData
//     })
//     tableData.value = res.data.data
//     dateList.value = res.data.date
//     eaChartss()
//   } catch (error) {
//     tableData.value = []
//   } finally {
//     loading.value = false
//   }
// }
const getTableYearData = async () => {
  loading.value = true
  try {
    searchData.dateType = "year"
    const res = await companyMonthlyTradeDataApi({
      id: searchData.id,
      dateType: "year",
      year: searchData.year,
      month: searchData.month
      // ...searchData
    })
    tableList.value = res.data.data
    yearList.total_enter_trade_amount = res.data.yearNum.total_enter_trade_amount
    yearList.total_out_trade_amount = res.data.yearNum.total_out_trade_amount
  } catch (error) {
    tableData.value = []
  } finally {
    loading.value = false
  }
}
const getTableLastYearData = async () => {
  loading.value = true
  try {
    searchData.dateType = "year"
    const res = await companyMonthlyTradeDataApi({
      id: searchData.id,
      dateType: "year",
      year: searchData.lastyear,
      month: searchData.month
      // ...searchData
    })
    tableLastList.value = res.data.data
    yearLastList.total_enter_trade_amount = res.data.yearNum.total_enter_trade_amount
    yearLastList.total_out_trade_amount = res.data.yearNum.total_out_trade_amount
  } catch (error) {
    tableLastList.value = []
  } finally {
    loading.value = false
  }
}
//#endregion

// const eaChartss = () => {
//   if (chartRef.value) {
//     const chartInstance = echarts.init(chartRef.value)
//     const option = {
//       tooltip: {},
//       legend: {
//         data: ["贴现", "买票"]
//       },
//       xAxis: [
//         {
//           type: "category",
//           data: dateList.value
//         }
//       ],
//       yAxis: [
//         // {
//         //   name: "单位：万元",
//         //   type: "value"
//         // }
//         {
//           name: "单位：万元",
//           type: "value",
//           scale: true, // 强制为连续坐标轴
//           min: 0, // 最小值
//           max: 200, // 最大值
//           splitNumber: 10, // 刻度数量
//           interval: 20, // 每个刻度的间隔
//           axisLabel: {
//             formatter: function (value: any) {
//               // 格式化刻度标签
//               return [10, 20, 30, 50, 100, 200, 300, 500].find((v) => v === value) || value
//             }
//           }
//         }
//       ],
//       series: tableData.value
//     }
//     chartInstance.setOption(option, true)
//   }
// }
const openDialogs = (row: any) => {
  console.log(row)
  console.log("openDialogs")
  if (eachartsRef.value) {
    eachartsRef.value.openDialog(row)
  }
}
</script>

<template>
  <el-dialog v-model="dialogVisible" title="列表" width="50%" :before-close="handleClose" draggable destroy-on-close>
    <el-card class="box-card" v-loading="loading" shadow="never">
      <template #header>
        <div class="boxHeader">
          {{ companyName }}
          <!-- {{ companyName + "(" + searchData.month + "月)" }} -->
        </div>
      </template>
      <div class="boxs">
        <!-- <div class="boxs-left">
          <div ref="chartRef" style="height: 400px" />
        </div> -->
        <div class="boxs-right">
          <div class="rights-bootom" style="">
            <el-date-picker
              v-model="searchData.lastyear"
              style="width: 100px"
              :clearable="false"
              type="year"
              placeholder="请选择年"
              format="YYYY"
              value-format="YYYY"
              @change="handleDatePickerChange"
            />
          </div>
          <div class="rights rights-title">
            <div class="items">月份</div>
            <div class="items">贴现金额</div>
            <div class="items">买票金额</div>
          </div>
          <div v-for="(item, index) in tableLastList" :key="index" class="rights">
            <div class="items">
              <el-button key="primary" type="primary" @click="handleDatePickerDate(item.date, 1)" text>
                {{ item.date }}
              </el-button>
            </div>
            <div class="items">{{ item.total_enter_trade_amount }}</div>
            <div class="items">{{ item.total_out_trade_amount }}</div>
          </div>
          <div class="rights rights-count">
            <div class="items">
              <!-- 占位符 -->
              合计
            </div>
            <div class="items">{{ yearLastList.total_enter_trade_amount }}</div>
            <div class="items">{{ yearLastList.total_out_trade_amount }}</div>
          </div>
        </div>
        <div class="boxs-right">
          <div class="rights-bootom">
            <el-date-picker
              v-model="searchData.year"
              style="width: 100px"
              :clearable="false"
              type="year"
              placeholder="请选择年"
              format="YYYY"
              value-format="YYYY"
              @change="handleDatePickerChange"
            />
          </div>
          <div class="rights rights-title">
            <div class="items">月份</div>
            <div class="items">贴现金额</div>
            <div class="items">买票金额</div>
          </div>
          <div v-for="(item, index) in tableList" :key="index" class="rights">
            <div class="items">
              <el-button key="primary" type="primary" @click="handleDatePickerDate(item.date, 2)" text>
                {{ item.date }}
              </el-button>
            </div>
            <div class="items">{{ item.total_enter_trade_amount }}</div>
            <div class="items">{{ item.total_out_trade_amount }}</div>
          </div>
          <div class="rights rights-count">
            <div class="items">
              <!-- 占位符 -->
              合计
            </div>
            <div class="items">{{ yearList.total_enter_trade_amount }}</div>
            <div class="items">{{ yearList.total_out_trade_amount }}</div>
          </div>
        </div>
      </div>

      <!-- <template #header>
        <div>
          <el-date-picker
            v-model="searchData.month"
            class="demo-form-inline"
            :clearable="false"
            type="month"
            placeholder="请选择月份"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
          <el-button type="primary" @click="getTableData">确认</el-button>
        </div>
      </template> -->
    </el-card>
    <eacharts ref="eachartsRef" />
  </el-dialog>
</template>

<style lang="scss" scoped>
.boxHeader {
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  font-size: 24px;
}
.box-card {
  margin-bottom: 10px;
  height: 100%;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.boxs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  .boxs-right {
    width: 45%;
    border: 1px solid #ccc;
    .rights {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // height: 20px;
      // margin-bottom: 10px;
      border-bottom: 1px solid #ccc;
      .items {
        width: 50%;
        text-align: center;
        // border: 1px solid #ccc;
      }
    }
    .rights-title {
      font-size: 16px;
      font-weight: bold;
      text-align: center;
      padding: 8px 0;
      border-bottom: 1px solid #ccc;
    }
    .rights-count {
      font-size: 16px;
      font-weight: bold;
      text-align: center;
      padding: 8px 0;
      border-bottom: 1px solid #ccc;
    }
    .rights-bootom {
      display: flex;
      justify-content: center;
      margin-top: 10px;
      margin-bottom: 10px;
    }
  }

  .boxs-left {
    height: 400px;
    width: 70%;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
.cursor—pointer {
  //鼠标放上去变手指
  cursor: pointer;
}
/* 强制设置 el-input 内部日期选择框加粗 */
::v-deep .el-input__wrapper .el-input__inner {
  font-weight: bold !important;
}
</style>
